package Socket;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.SocketException;
import java.util.Scanner;

public class Socket03 {
    public static void main(String[] args) {

        SendThread st = new SendThread();
        ReceiveThread rt = new ReceiveThread();
        Thread t1 = new Thread(st);
        Thread t2 = new Thread(rt);
        t1.start();
        t2.start();

    }
}



class ReceiveThread implements Runnable{
    @Override
    public void run() {
        //创建接收端Socket对象
        try {
            DatagramSocket ds = new DatagramSocket(9999);
            //创建数据包 循环接收
            while (true){
                //创建一个字节数组临时存储
                byte[] bys = new byte[1024];
                //创建packet数据包
                DatagramPacket dp = new DatagramPacket(bys,bys.length);
                //接收数据   使用datagramSocket 接收数据到 datagramPacket中
                ds.receive(dp);
                //解析数据
                //直到发来主机的IP地址   接收的数据
                String ip = dp.getAddress().getHostAddress();
                String s = new String(dp.getData(),0,dp.getLength(),"utf-8");
                System.out.println(ip+"发来的信息是:"+s);
                if ("bye".equals(s)){
                    System.out.println("聊天室关闭");
                    ds.close();
                    break;
                }



            }




        } catch (Exception e) {
            e.printStackTrace();
        }

    }





}


class SendThread implements Runnable{



    @Override
    public void run() {
        //创建Socket对象
        try {
            DatagramSocket ds = new DatagramSocket();
            Scanner scan = new Scanner(System.in);

            while (true){
                System.out.print("请输入：");
                String str = scan.nextLine();
                DatagramPacket packet = new DatagramPacket(str.getBytes(),str.getBytes().length,
                        InetAddress.getByName("127.0.0.1"),9999);
                ds.send(packet);
                if ("bye".equals(str)){
                    break;
                }
            }



        } catch (Exception e) {
            e.printStackTrace();
        }


    }
}
